﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Compiler
{
    public class Parser
    {
        private ParseTable parseTable;
        private Lexer lexer;
        private INodeFactory nodeFactory;

        public Parser(ParseTable parseTable, Lexer lexer, INodeFactory nodeFactory)
        {
            this.parseTable = parseTable;
            this.lexer = lexer;
            this.nodeFactory = nodeFactory;
        }

        public void SetSource(string Source)
        {
            lexer.SetSource(Source);
        }

        public void DoParse()
        {
            //: wie accept behandeln? error ist leicht -> exception, aber ist das auch bei accept i.O.?

            Stack<INode> nodeStack = new Stack<INode>();

            Stack<Entry> stack = new Stack<Entry>();
            stack.Push(new Entry(parseTable.Start, Symbol.EOF));

            //stack.print();

            IEnumerator<LexerPair> sourceEnumerator = lexer.GetEnumerator();
            sourceEnumerator.MoveNext();

            while (stack.Count > 0)
            {
                SimpleParseTableState state = stack.Peek().state;

                LexerPair lexPair = sourceEnumerator.Current;
                Symbol input = lexPair.Token.Terminal;  // lexer.Peek();

                ParseTableAction action;

                if (lexPair.Token == Token.Unknown)
                    throw new UnknownLexeme { lexerPair = lexPair };
                else if (parseTable.TryGetAction(state, input, out action))
                {
                    //Console.WriteLine(state.ToString() + " / " + input.ToString());
                    //Console.WriteLine("action: {0}", action.ToString());

                    Debug.Assert(input == sourceEnumerator.Current.Token.Terminal);// lexer.Peek());
                    action.Execute(sourceEnumerator, stack, nodeStack, nodeFactory);

                    //Console.WriteLine();
                    //stack.print();
                }
                else
                    throw new NotAcceptException { RestOfSource = lexer.GetRestOfSource() };
            }
        }
    }
}
